
<template>
  <div>
    <h3>发表评论</h3>
    <hr>
    <textarea name id placeholder="请输入要评论的内容（不超过120个字）" maxlength="120" v-model="msg"></textarea>
    <mt-button type="primary" size="large" @click="postComent">发表评论</mt-button>
    <div class="cmt-list">
      <div class="cmt-item" v-for="(item,index) in comments" :key="index">
        <div
          class="cmt-title"
        >第{{index+1}}楼&nbsp;&nbsp;用户:{{item.user_name}}&nbsp;&nbsp;发表时间:{{item.add_time|timeFormat('YYYY-MM-DD')}}</div>
        <div class="cmt-content">{{item.content?item.content:"此用户很懒，什么都没留下"}}</div>
      </div>
    </div>
    <mt-button type="danger" size="large" plain @click="getMore">加载更多</mt-button>
  </div>
</template>
<script>
import { Toast } from "mint-ui";
export default {
  data() {
    return {
      pageIndex: 1, //默认展示第一页数据
      comments: [],
      msg: "" //评论输入的内容
    };
  },
  methods: {
    getComents() {
      this.$http
        .get(
          "api/getcomments/" + this.parentId + "?pageindex=" + this.pageIndex
        )
        .then(function(res) {
          if (res.body.status !== 0) {
            return Toast("获取评论失败");
          }
          this.comments = this.comments.concat(res.body.message); //concat 元数组不变。拼接完之后一定要赋值
        });
    },
    getMore() {
      this.pageIndex++;
      this.getComents();
    },
    postComent() {
      // 检验内容
      if (!this.msg.trim()) {
        return Toast("评论内容不能为空");
      }
      this.$http
        .post("api/postcomment/" + this.parentId, {
          content: this.msg.trim()
        })
        .then(function(res) {
            if(res.body.status!==0){
                return Toast('发表评论失败,请稍后再试')
            }
            Toast(res.body.message)
            var cmt={user_name:'匿名用户',add_time:Date.now(),content:this.msg.trim()}
            this.comments.unshift(cmt)
            this.msg=''
        });
    }
  },
  props: ["parentId"],
  created() {
    this.getComents();
  }
};
</script>
<style lang="scss" scoped>
h3 {
  font-size: 18px;
}
textarea {
  font-size: 14px;
  height: 85px;
  margin: 0;
}
.cmt-list {
  font-size: 13px;

  .cmt-item {
    margin: 5px;
    .cmt-title {
      line-height: 30px;
      background: #ccc;
    }
    .cmt-content {
      text-indent: 2em;
    }
  }
}
</style>
